package com.dirk.happie.activities;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.dirk.happie.R;
import com.dirk.happie.adapters.ArticlesListAdapter;
import com.dirk.happie.beans.ArticleBean;
import com.dirk.happie.network.GetArticlesTask;
import com.dirk.happie.network.RequestCompleteListener;
import com.dirk.happie.utils.App;
import com.dirk.happie.utils.Availablity;
import com.dirk.happie.utils.Common;
import com.dirk.happie.utils.Keys;
import com.dirk.happie.utils.LogoDownloader;

public class ArticlesActivity extends Activity {
	ArrayList<ArticleBean> product_data;

	private App mApp;

	private String categoryId;
	// private String companyId;
	// List<ArticleBean> articles;
	private ArticlesListAdapter adapter = null;

	private GetArticlesTask getArticlesTask = null;

	private LogoDownloader logoDownloader = null;
	private String cacheFolderPath = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_article);
		this.mApp = ((App) getApplication());
		ImageView companyLogoView = (ImageView) findViewById(R.id.img_company);
		cacheFolderPath = Environment.getExternalStorageDirectory().getPath() + "/happie_cache";
		File file = new File(cacheFolderPath);
		file.mkdirs();
		logoDownloader = new LogoDownloader();

		if (mApp.getCompanyLogo() != null) {
			logoDownloader.download(Keys.LOGOS_URL + mApp.getCompanyLogo(), cacheFolderPath + "/" + Common.getMD5(mApp.getCompanyLogo()), companyLogoView);
		}
		product_data = new ArrayList<ArticleBean>();

		categoryId = getIntent().getStringExtra(Keys.KEY_CATEGORY_ID);
		// companyId = getIntent().getStringExtra(Keys.KEY_COMPANY_ID);

		parseArticlesJSON();

		footerMenuListeners();
	}

	private void createListView() {
		ListView lv = (ListView) findViewById(R.id.listProducts);
		adapter = new ArticlesListAdapter(this, R.layout.article_list_item, product_data);
		lv.setFastScrollEnabled(true);
		lv.setScrollingCacheEnabled(false);
		lv.setAdapter(adapter);
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Intent intent = new Intent(ArticlesActivity.this, ArticleSizeActivity.class);
				intent.putExtra(Keys.KEY_CATEGORY_ID, product_data.get(position).getCategoryId());
				intent.putExtra(Keys.KEY_ARTICLE_ID, product_data.get(position).getArticleId());
				// intent.putExtra(Keys.KEY_COMPANY_ID, companyId);
				startActivityForResult(intent, 10);
			}
		});
	}

	private void compareAtriclecByOffer(List<ArticleBean> articleList) {

		for (ArticleBean curArticle : articleList) {
			curArticle.setOfferCompare("1");
			if (Common.compareOfferDate(curArticle)) {
				curArticle.setOfferCompare("0");
			}
		}

		Collections.sort(articleList, new Comparator<ArticleBean>() {
			public int compare(ArticleBean a, ArticleBean b) {
				return a.getOfferCompare().compareToIgnoreCase(b.getOfferCompare());
			}
		});

	}

	private void parseArticlesJSON() {

		getArticlesTask = new GetArticlesTask(this);
		getArticlesTask.setRequestCompleteListener(new RequestCompleteListener<List<ArticleBean>>() {

			@Override
			public void onSuccess(List<ArticleBean> result) {
				if (result != null) {
					compareAtriclecByOffer(result);
					for (int i = 0; i < result.size(); i++) {
						product_data.add(result.get(i));
					}
				}

				createListView();
			}

			@Override
			public void onFailure(final String message) {
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
					}
				});
			}
		});

		if (Availablity.isNetworkAvailable(this)) {
			getArticlesTask.execute(categoryId);
		} else {
			Toast.makeText(this, getString(R.string.no_connection), Toast.LENGTH_SHORT).show();
		}
	}

	private void footerMenuListeners() {

		View homeButton = findViewById(R.id.home);
		homeButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setResult(100);
				finish();
			}
		});

		View categoriesButton = findViewById(R.id.categories);
		categoriesButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		View basketButton = findViewById(R.id.basket);
		basketButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(ArticlesActivity.this, BasketActivity.class);
				intent.putExtra(Keys.KEY_COMPANY_ID, mApp.getCompanyId());
				startActivityForResult(intent, 10);
			}
		});

		View searchButton = findViewById(R.id.search);
		searchButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

			}
		});

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		setResult(resultCode);
		switch (resultCode) {
		case 100:
			finish();
			break;

		case 200:
			finish();
			break;

		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (logoDownloader != null) {
			logoDownloader.clearImages();
		}
		if (getArticlesTask != null) {
			getArticlesTask.setRequestCompleteListener(null);
		}
		if (adapter != null) {
			adapter.clearResources();
		}
	}

}
